<?php

m2import("model/entity/SimpleViewerGalleryEntity.php");

/*
    Action configuration: 
        <conf:action mapping="simpleViewerGallery" class="SimpleViewerGalleryAction" methodmapping="true" bypassViewMapping="true">
        </conf:action>
*/
class SimpleViewerGalleryAction extends phpinchains_WebAction {

    function index (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $this->dispatch("simpleViewerGallery::listing", $actionform);
    }

    function listPart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ($actionform->get('redirect')) {
            $env->setSession('redirect_simpleviewergallery', $actionform->get('redirect'));
        }
        $entity = new SimpleViewerGalleryEntity($actionform, null);
        $pagesize = 20;
        $actionform->set("pagesize", $pagesize);
        
        $pagername = 'simpleviewergalleryPager';
        // Save pager value in session
        if ($actionform->get($pagername)) {
            $env->setSession($pagername, $actionform->get($pagername));
        }
        $actionform->set($pagername, $env->getSession($pagername));
        $offset = ($env->getSession($pagername) ? ($pagesize * (int) $env->getSession($pagername)) - $pagesize : 0);
        
        // sorting
        $sortingname = 'simpleviewergallerySorting';
        if ($actionform->get($sortingname) && $entity->hasField($actionform->get($sortingname), true)) {
            $sorting = $env->getSession($sortingname);
            if ($sorting[0] == $actionform->get($sortingname) && (empty($sorting[1]) || $sorting[1] == 'asc')) {
               $sorting[1] = 'desc';
            } else {
                $sorting = array($actionform->get($sortingname));
            }
            $env->setSession($sortingname, $sorting);
        }
        if (!$env->getSession($sortingname)) {
            $env->setSession($sortingname, array('id'));
        }
        $actionform->set('sorting', $env->getSession($sortingname));
        

        
            $env->setSession("searchactiveSimpleViewerGallery", false);
            $actionform->set("objList", $entity->findByFields(array(), 'AND', array(
                'limit' => $pagesize, 
                'joinreferenced' => true,
                'offset' => $offset,
                'orderby' => join(' ', $env->getSession($sortingname))
                )
            ));
            $count = $entity->findByFields(array(), 'AND', array(
                'fields' => "count(*) as count",
                'joinreferenced' => true,
                )
            );
        
        $actionform->set("count", $count['0']['count']);
        $actionform->set('simpleviewergallery_openCategories', $env->getSession("searchactiveSimpleViewerGallery")?$env->getSession('searchactiveSimpleViewerGallery_openCategories'):$env->getSession('simpleviewergallery_openCategories'));
    }

    function listing (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'simpleViewerGallery::listing');
    }

    function createForm (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'simpleViewerGallery::createForm');
        $actionform->set("formAction", "create");
        $this->_loadReferenced('create');
        if (!$actionform->get('svgthumb_h'))
            $actionform->set('svgthumb_h', 65);
        if (!$actionform->get('svgthumb_w'))
            $actionform->set('svgthumb_w', 65);
        if (!$actionform->get('svgdetail_h'))
            $actionform->set('svgdetail_h',400);
        if (!$actionform->get('svgdetail_w'))
            $actionform->set('svgdetail_w',400);
        return "form";
    }
    
    function create (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'simpleViewerGallery::create');
        $this->constrainIncomingView("simpleViewerGallery/form", "form");
        if ($actionform->get("abort")) {
            $this->_formDispatch($actionform);
        } elseif ($this->validate()) {
            $entity = new SimpleViewerGalleryEntity($actionform, null);
            $formdata = $this->getFormdata("","",true);
            $entity->create($formdata);
            $env->setAttribute("actionmsg", "actionmsg_obj_created");
            $this->_formDispatch($actionform);
        } else {
            $this->dispatch("simpleViewerGallery::createForm", $actionform);
        }
    }

    function edit (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'simpleViewerGallery::edit');
        if ((int) $actionform->get("id")) {
            $entity = new SimpleViewerGalleryEntity($actionform, null);
            $actionform->set("formAction", "save");
            $actionform->set("editObj", $entity->findByPrimaryKey($actionform->get("id")));
            $this->_loadReferenced('edit');
            return "form";
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_edit");
            $this->_formDispatch($actionform);
        }
    }
    
    function save (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $this->constrainIncomingView("simpleViewerGallery/form", "form");
        if ($actionform->get("abort")) {
            $this->_formDispatch($actionform);
        } elseif ($this->validate()) {
            $entity = new SimpleViewerGalleryEntity($actionform, null);
            $formdata = $this->getFormdata("", "", true);
            $entity->update($formdata);
            $env->setAttribute("actionmsg", "actionmsg_obj_saved");
            $this->_formDispatch($actionform);
        } else {
            $this->dispatch("simpleViewerGallery::edit", $actionform);
        }
    }

    function delete (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ((int) $actionform->get("id")) {
            $entity = new SimpleViewerGalleryEntity($actionform, null);
            $entity->delete((int) $actionform->get("id"));
            $env->setAttribute("actionmsg", "actionmsg_obj_deleted");
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_delete");
        }
        $this->_dispatchListing();
    }

    function show (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'simpleViewerGallery::show');
        $id = !$actionform->get('id')?$env->getSession("selectedObj_simpleviewergallery_id"):$actionform->get('id');
        if ((int) $id) {
            $entity = new SimpleViewerGalleryEntity($actionform, null);
            $this->_loadReferenced('show');
            $actionform->set("displayObj", $entity->findByPrimaryKey((int) $id, array("joinreferenced" => true, 'cascade-selfref' => true)));
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_show");
            $this->dispatch("simpleViewerGallery::listing", $actionform);
        }
    }

    function _formDispatch ($actionform) {
        if ($actionform->get('caller') == 'show') {
            $this->dispatch("simpleViewerGallery::show", $actionform);
        } elseif ($this->env->getSession('redirect_simpleviewergallery')) {
            $this->dispatch($this->env->getSession('redirect_simpleviewergallery'), $actionform);
        } else {
            $this->dispatch("simpleViewerGallery::show", $actionform);
        }
    }

    function _dispatchListing () {
        $actionform = new phpinchains_Actionform();
        if ($this->env->getSession('redirect_simpleviewergallery')) {
            $this->dispatch($this->env->getSession('redirect_simpleviewergallery'), $actionform);
        } else {
            $this->dispatch('simpleViewerGallery::listing', $actionform);
        }
    }
    
    function _handleFilter ($name) {
        if ($this->actionform->get("simpleViewerGalleryfilterReset") == "true") {
            $this->env->setSession($name, null);
            $this->env->setSession('searchactiveSimpleViewerGallery_openCategories', null);
        }
        if ($this->actionform->get($name) && !$this->actionform->get('reset')) {
            $fields = $this->actionform->get($name);
            $set = false;
            foreach ($fields as $n => $v) {
                if (strlen($v)) {
                    $set = true;
                    break;
                }
            }
            if ($set) {
                $this->env->setSession($name, $this->actionform->get($name));
            }
        }
        $this->actionform->set($name, $this->env->getSession($name));
    }

    function _preProcess ($methodname, env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform, $outsidecall) {
        // prevent setting rootAction from the outside
        if ($outsidecall) {
            $actionform->set('rootAction', '');
        }
        if (in_array($methodname, array("show", "edit")) && $outsidecall) {
            if ($actionform->get("id"))
                $env->setSession("selectedObj_simpleviewergallery_id", $actionform->get("id"));
        }
        
        // allow a preprocess method in the mix-ins
        if (method_exists($this, '_afterPreProcess')) {
            $this->_afterPreProcess($methodname, $env, $viewmapping, $actionform);
        }
    }
    
    function _loadReferenced ($caller) {

    }


    private function _getImportPath () {
        return base_ApplicationContext::getInstance()->cfgPath('simpleViewerGallery','path').'import';
    }

    private function _getExportPath () {
        return base_ApplicationContext::getInstance()->cfgPath('simpleViewerGallery','path').'export';
    }

    public function importFolder (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $id = !$actionform->get('id')?$env->getSession("selectedObj_simpleviewergallery_id"):$actionform->get('id');
        if ((int) $id) {
            $dir = dir($this->_getImportPath());
            if ($dir) {
                $actionform->set('importdir', $this->_getImportPath());
                $actionform->set('gallery_id', $id);
                $folderlist = array();
                while (false !== ($entry = $dir->read())) {
                    if ($entry[0] != '.')
                        $folderlist[] = array('folder' => $entry);
                }
                $dir->close();
                $actionform->set('folderlist', $folderlist);
            }
        }
    }

    public function doImportFolder (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        m2import("model/entity/SimpleViewerGalleryImageEntity.php");
        $foldername = $this->_getImportPath().'/'.$actionform->get('foldername');
        $dir = dir($foldername);
        if ($dir) {
            $entity = new SimpleViewerGalleryImageEntity($actionform, null);
            while (false !== ($entry = $dir->read())) {
                if ($entry[0] != '.') {
                    $stats = stat($foldername.'/'.$entry);
                    $entity->create(array(
                            'sviimage' => file_get_contents($foldername.'/'.$entry),
                            'sviimage_filename' => $entry,
                            'sviimage_type' => 'image/jpeg',
                            'sviimage_size' => $stats['size'],
                            'simpleViewerGallery_id' => $actionform->get('id')
                    ));
                }
            }
            $dir->close();
            $env->setAttribute("actionmsg", "actionmsg_folder_imported");
        } else {
            $env->setAttribute("actionmsg", "actionmsg_folder_does_not_exist");
            $env->setAttribute("actionmsgparam", $foldername);
        }
        $this->dispatch('simpleViewerGallery::show', $actionform);
    }

    private function _saveResizedImage ($imagesource, $resizeW, $resizeH, $destfilename) {
        $source = @imagecreatefromstring($imagesource);
        $width  = @imagesx($source);
        $height = @imagesy($source);
        $newwidth  = $resizeW;
        $newheight = round($height * ($resizeW / $width));
        /** use resizeH and resizeW as constraints **/
        if ($newheight > $resizeH) {
            $newheight = $resizeH;
            $newwidth = round($width * ($resizeH / $height));;
        }
        $thumb = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        imagejpeg($thumb, $destfilename);
    }

    public function doExportGallery (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $id = !$actionform->get('id')?$env->getSession("selectedObj_simpleviewergallery_id"):$actionform->get('id');
        if ((int) $id) {
            if (!file_exists($this->_getExportPath().'/gallery'.$id)) mkdir($this->_getExportPath().'/gallery'.$id);
            m2import("model/entity/SimpleViewerGalleryImageEntity.php");
            $entity = new SimpleViewerGalleryImageEntity($actionform, null);
            $entityGallery = new SimpleViewerGalleryEntity($actionform, null);
            $gallery = $entityGallery->findByPrimaryKey($id);
            $rows = $entity->findBy('simpleViewerGallery_id', (int) $id,
                array(
                    'fields' => 'id',
                    'orderby' => 'svisorting, id'
                )
            );
            $field = 'sviimage';
            if (!file_exists($this->_getExportPath().'/gallery'.$id.'/thumb')) mkdir($this->_getExportPath().'/gallery'.$id.'/thumb');
            if (!file_exists($this->_getExportPath().'/gallery'.$id.'/images')) mkdir($this->_getExportPath().'/gallery'.$id.'/images');
            $imagedata = array();
            foreach ($rows as $row) {
                $image = $entity->findByPrimaryKey($row['id'],array("fields" => "$field,{$field}_type,{$field}_size,{$field}_filename,{$field}_filename,svidescription"));
                $this->_saveResizedImage($image['sviimage'], $gallery['svgthumb_w'], $gallery['svgthumb_h'], $this->_getExportPath().'/gallery'.$id.'/thumb/'.$row['id'].'_'.$image['sviimage_filename']);
                $this->_saveResizedImage($image['sviimage'], $gallery['svgdetail_w'], $gallery['svgdetail_h'], $this->_getExportPath().'/gallery'.$id.'/images/'.$row['id'].'_'.$image['sviimage_filename']);
                $imagedata[] = array(
                    'filename' => $row['id'].'_'.$image['sviimage_filename'],
                    'caption' => $image['svidescription']
                );
            }
            $this->_createGalleryXML($id, $imagedata, $gallery);
            $env->setAttribute("actionmsg", "actionmsg_gallery_exported");
            $env->setAttribute("actionmsgparam", count($rows));
            $this->dispatch('simpleViewerGallery::show', $actionform);
        } else {
            $env->setAttribute("actionmsg", "actionmsg_gallery_could_not_export");
            $this->dispatch('simpleViewerGallery::show', $actionform);
        }
    }

    private function _createGalleryXML ($id, $imagedata, $gallery) {
        $ctx = base_ApplicationContext::getInstance();
        $cnffilepath = $this->_getExportPath().'/gallery'.$id.'/gallery.xml';
        if (file_exists($cnffilepath))
            unlink($cnffilepath);
        copy($ctx->modPath('simpleViewerGallery').'files/gallery.xml', $cnffilepath);
        print file_get_contents($cnffilepath);
        try {
            $xml = new SimpleXMLElement(file_get_contents($cnffilepath));
            $xml['imagePath'] = $ctx->cfgPath('simpleViewerGallery','url').'export/gallery'.$id.'/images/';
            $xml['thumbPath'] = $ctx->cfgPath('simpleViewerGallery','url').'export/gallery'.$id.'/thumb/';
            $xml['maxImageWidth'] = $gallery['svgdetail_w'];
            $xml['maxImageHeight'] = $gallery['svgdetail_h'];
            unset($xml->image);
            foreach ($imagedata as $image) {
                $imgElem = $xml->addChild('image');
                $imgElem->addChild('filename',$image['filename']);
                $imgElem->addChild('caption', utf8_encode($image['caption']));
            }
            $xml->asXML($cnffilepath);
        } catch (Exception $e) {
            env::getInstance()->setAttribute('actionmsg', 'actionmsg_xml_creation_error');
        }
    }


}
    

?>